package com.tuyan.aixiang.util;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


public class AESUtil {

    private static final String TAG = "AESUtil";
    private static final String KEY = "bbcacb684efa4bc6";

    // 加密
    public static String encrypt(String sSrc, String sKey) throws Exception {

        if(sSrc == null) {
            return null;
        }
        if (sKey == null) {
            Log.w(TAG, "key is null, use default key");
//            return null;
            sKey = KEY;
        }

        // 判断Key是否为16位
        if (sKey.length() != 16) {
            Log.w(TAG, "key length not 16");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

        return Base64.encodeToString(encrypted, Base64.DEFAULT);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    // 解密
    public static String decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                Log.w(TAG, "key is null, use default key");
//                return null;
                sKey = KEY;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                Log.w(TAG, "key length not 16");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = Base64.decode(sSrc, Base64.DEFAULT);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                return new String(original, "utf-8");
            } catch (Exception e) {
                Log.e(TAG, e);
                return null;
            }
        } catch (Exception ex) {
            Log.e(TAG, ex);
            return null;
        }
    }
}